//
//  Utils.swift
//  Game
//
//  Created by woniu on 2025/8/25.
//

import Foundation
import UIKit
import AVFoundation
import AudioToolbox

struct Utils {
    // 语音合成器
    private static let synthesizer = AVSpeechSynthesizer()
    //是否使用音效
    public static var isEnableSound = true
    
    static func isPad() -> Bool {
        return UIDevice.current.userInterfaceIdiom == .pad
    }

    static func isPhone() -> Bool {
        return UIDevice.current.userInterfaceIdiom == .phone
    }
    
    
    /// 读单词
    public static func play(word:String){
        let utterance = AVSpeechUtterance(string: word)
        utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
        utterance.rate = 0.3
        utterance.pitchMultiplier = 1.2
        synthesizer.speak(utterance)
    }
    
    /// 读单词
    public static func play(sentence:String){
        let utterance = AVSpeechUtterance(string: sentence)
        utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
        utterance.rate = 0.2
        utterance.pitchMultiplier = 1.2
        synthesizer.speak(utterance)
    }
    
    /// 播放音效
    public static func play(sound:Int){
        if isEnableSound == true{
            AudioServicesPlaySystemSound(SystemSoundID(sound))
        }
    }
    
    /// 播放翻动卡片
    public static func playCardSound(){
        play(sound: 1158)
    }
    
    /// 错误
    public static func playErrorSound(){
        play(sound: 1128)//1165
    }
    
    /// 正确
    public static func playSuccessSound(){
        play(sound: 1167)
    }
    
    //点击声音
    public static func playTapSound(){
        play(sound: 1103)//1155
    }
    
    //弹框提示
    public static func alert(msg:String){
        let alert = UIAlertController(title:"提示", message:msg, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        MyNavigator.getTopVC()?.present(alert, animated: true)
    }
    
    public static func arrayStringToJson(_ array: [String]) -> String? {
        // 检查数组是否可序列化为JSON
        guard JSONSerialization.isValidJSONObject(array) else {
            print("数组不可序列化为JSON")
            return nil
        }
        
        do {
            // 将数组序列化为Data
            let jsonData = try JSONSerialization.data(withJSONObject: array, options: [])
            
            // 将Data转换为字符串
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                return jsonString
            } else {
                print("无法将JSON数据转换为字符串")
                return nil
            }
        } catch {
            print("JSON序列化失败: \(error.localizedDescription)")
            return nil
        }
    }
}
